package itsm.isperp.framework.web.servlet;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.web.servlet.http.ParameterHttpServletRequestWrapper;

import java.io.IOException;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.sitemesh.builder.SiteMeshFilterBuilder;
import org.sitemesh.config.ConfigurableSiteMeshFilter;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2013-9-11
 * @since 1.0
 * 
 */
@WebFilter(asyncSupported = true)
public class SitemeshFilter extends ConfigurableSiteMeshFilter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		super.init(filterConfig);

	}

	protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
		Set<String> sets = ContextHolder.getAuthorityResourceDefinition()
				.keySet();
		for (String url : sets) {
			if (url.indexOf("/") != 0)
				builder.addDecoratorPath("/" + url,
						"/WEB-INF/jsp/includes/edit.jsp");
			else {
				builder.addDecoratorPath(url, "/WEB-INF/jsp/includes/edit.jsp");
			}
		}
		ContextHolder.setAuthorityResourceDefinitionReloaded(false);

	}

	@Override
	protected boolean reloadRequired() {
		return super.reloadRequired()
				|| ContextHolder.getAuthorityResourceDefinitionReloaded();
	}

	@Override
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		if (servletRequest instanceof HttpServletRequest) {

			HttpServletRequest request = (HttpServletRequest) servletRequest;
			String target = request.getRequestURI();

			if (target.indexOf("/websocket") >= 0) {
				filterChain.doFilter(request, servletResponse);

			} else if (target.indexOf("/ReportServer") >= 0) {
				filterChain.doFilter(request, servletResponse);
			} else {

				request.setCharacterEncoding("UTF-8");
				HttpServletRequestWrapper hw = new ParameterHttpServletRequestWrapper(
						request);
				hw.setCharacterEncoding("UTF-8");

				super.doFilter(hw, servletResponse, filterChain);
			}

		}

	}
}
